import 'package:flutter/material.dart';
import 'package:flutter_app_demo/podo/movie_model.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;


class HttpDemo extends MaterialPageRoute<Null> {
    HttpDemo()
        : super(builder: (BuildContext ctx) {
        return Scaffold(
            appBar: AppBar(
                title: Text("2 way Http demo"),
            ),
            body: HttpDemoPage(),
        );
    });
}

class HttpDemoPage extends StatefulWidget {
    HttpDemoPage({Key key}) : super(key: key);
    
    @override
    State<StatefulWidget> createState() {
        return HttpDemo2State(); //注释此处以切换不同方式
        //return HttpDemo1State();
    }
}

//请求网络第一种方式
class HttpDemo1State extends State<HttpDemoPage> {
    final String url = "http://api.douban.com/v2/movie/top250";
    List data;
    
    @override
    Widget build(BuildContext context) {
        return ListView.builder(
            itemCount: data == null ? 0 : data.length,
            itemBuilder: (BuildContext ctx, int index) {
                return InkWell(
                    onTap: () {
                        Scaffold.of(context)
                            ..removeCurrentSnackBar()
                            ..showSnackBar(SnackBar(
                                content: Text(data[index]["title"]),
                            ));
                    },
                    child: Container(
                        padding: EdgeInsets.all(10.0),
                        margin: EdgeInsets.all(5),
                        child: Row(children: <Widget>[
                            Text(data[index]["title"]),
                        ]),
                    ),
                );
            },
        );
    }
    
    void initState() {
        super.initState();
        getTop250DataWay1();
    }
    
    Future<String> getTop250DataWay1({int start: 0, int count: 25}) async {
        var res = await http.post(Uri.encodeFull(url), body: {"start": "$start", "count": "$count"});
        setState(() {
            var movie = json.decode(res.body);
            data = movie['subjects'];
        });
        return "network ok";
    }
}

//请求网络第二种方式
class HttpDemo2State extends State<HttpDemoPage> {
    StreamController<NetResult> streamController;
    List<Movie> data = [];
    
    @override
    void initState() {
        super.initState();
        streamController = StreamController.broadcast();
        streamController.stream.listen(
            //
                (onData) => setState(() => data.addAll(onData.subjects)),
            //
            onError: (e) {
                print(e.toString());
            });
        loadData();
    }
    
    loadData() async {
        final String url = "http://api.douban.com/v2/movie/top250?start=0&count=25&apikey=0df993c66c0c636e29ecbb5344252a4a";
        var client = http.Client();
        var req = http.Request('get', Uri.parse(url));
        var streamedRes = await client.send(req);
        
        streamedRes.stream //
            .transform(Utf8Decoder())
            .transform(JsonDecoder())
            .take(1) //可不加take(1)
            .map((map) => NetResult.cjz(map))
            .pipe(streamController);
    }
    
    @override
    void dispose() {
        streamController?.close();
        super.dispose();
        streamController = null;
    }
    
    @override
    Widget build(BuildContext context) {
        return ListView.builder(
            itemCount: data == null ? 0 : data.length,
            itemBuilder: (BuildContext ctx, int index) {
                if (index >= data.length) {
                    return null;
                }
                return InkWell(
                    onTap: () {
                        Scaffold.of(context)
                            ..removeCurrentSnackBar()
                            ..showSnackBar(SnackBar(
                                content: Text(data[index].title),
                            ));
                    },
                    child: Container(
                        padding: EdgeInsets.all(10.0),
                        margin: EdgeInsets.all(5),
                        child:
                        // FittedBox(
                        //     fit: BoxFit.fitWidth,
                        //     child:
                        Row(children: <Widget>[
                            Text(data[index].title),
                            Spacer(),
                            Image.network(
                                data[index].images.medium,
                                width: 150.0,
                            ),
                        ]
                            // )
                        ),
                    ),
                );
            },
        );
    }
}
